#version 450

layout (binding = 0) uniform sampler2D InColorTexture;

layout (location = 0) in vec2 inUV;
layout (location = 0) out vec4 outColor;

//算法代码来自：
//https://github.com/mattdesl/glsl-fxaa/blob/master/fxaa.glsl
//MIT License

#ifndef FXAA_REDUCE_MIN
    #define FXAA_REDUCE_MIN   (1.0/ 128.0)
#endif
#ifndef FXAA_REDUCE_MUL
    #define FXAA_REDUCE_MUL   (1.0 / 8.0)
#endif
#ifndef FXAA_SPAN_MAX
    #define FXAA_SPAN_MAX     8.0
#endif

void main()
{
    vec2 resolution = vec2(textureSize(InColorTexture, 0));
    vec2 invResolution = 1.0 / resolution;

    vec3 rgbNW = texture(InColorTexture, inUV + vec2(-1.0, -1.0) * invResolution).rgb;
    vec3 rgbNE = texture(InColorTexture, inUV + vec2(1.0, -1.0) * invResolution).rgb;
    vec3 rgbSW = texture(InColorTexture, inUV + vec2(-1.0, 1.0) * invResolution).rgb;
    vec3 rgbSE = texture(InColorTexture, inUV + vec2(1.0, 1.0) * invResolution).rgb;
    vec3 rgbM = texture(InColorTexture, inUV).rgb;


    vec3 luma = vec3(0.2126, 0.7152, 0.0722);
    float lumaNW = dot(rgbNW, luma);
    float lumaNE = dot(rgbNE, luma);
    float lumaSW = dot(rgbSW, luma);
    float lumaSE = dot(rgbSE, luma);
    float lumaM = dot(rgbM, luma);

    float lumaMin = min(lumaM, min(min(lumaNW, lumaNE), min(lumaSW, lumaSE)));
    float lumaMax = max(lumaM, max(max(lumaNW, lumaNE), max(lumaSW, lumaSE)));

    //亮度差异太小，不做抗锯齿
    if(lumaMax - lumaMin < 0.1)
    {
        outColor = vec4(rgbM, 1.0);
        return;
    }

    vec2 dir;
    dir.x = -((lumaNW + lumaNE) - (lumaSW + lumaSE));
    dir.y = ((lumaNW + lumaSW) - (lumaNE + lumaSE));

    float dirReduce = max((lumaNW + lumaNE + lumaSW + lumaSE) * (0.25 * FXAA_REDUCE_MUL), FXAA_REDUCE_MIN);

    float rcpDirMin = 1.0 / (min(abs(dir.x), abs(dir.y)) + dirReduce);
    dir = min(vec2(FXAA_SPAN_MAX, FXAA_SPAN_MAX),
              max(vec2(-FXAA_SPAN_MAX, -FXAA_SPAN_MAX),
              dir * rcpDirMin)) * invResolution;

    vec3 rgbA = 0.5 * (
        texture(InColorTexture, inUV + dir * (1.0 / 3.0 - 0.5)).rgb +
        texture(InColorTexture, inUV + dir * (2.0 / 3.0 - 0.5)).rgb);

    vec3 rgbB = rgbA * 0.5 + 0.25 * (
        texture(InColorTexture, inUV + dir * -0.5).rgb +
        texture(InColorTexture, inUV + dir * 0.5).rgb); 

    float lumaB = dot(rgbB, luma);

    if((lumaB < lumaMin) || (lumaB > lumaMax))
    {
        outColor = vec4(rgbA, 1.0);
    }
    else
    {
        outColor = vec4(rgbB, 1.0);
    }

}